package com.cyp.livelog.web;

import com.cyp.livelog.bean.User;
import com.cyp.livelog.utils.DbUtils;
import com.mysql.jdbc.StringUtils;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description
 */
@WebServlet("/login")
public class LoginAction extends HttpServlet {

  //前往页面
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.getRequestDispatcher("/login.jsp").forward(req, resp);
  }

  //登录操作
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");
    String username = req.getParameter("username");
    String password = req.getParameter("password");
    if (StringUtils.isNullOrEmpty(username) || StringUtils.isNullOrEmpty(username)) {
      req.setAttribute("message", "账号或密码不能为空！");
      req.getRequestDispatcher("/login.jsp").forward(req, resp);
      return;
    }
    ResultSet res = DbUtils.query("select * from user where username=? and password=?", username, password);
    try {
      if (res.next()) {
        User user = new User();
        user.setUsername(res.getString("username"));
        user.setNickname(res.getString("nickname"));
        req.getSession().setAttribute("user", user);
        req.getSession().setAttribute("isLogin", true);
        resp.sendRedirect(req.getContextPath() + "/home");
        return;
      } else {
        req.setAttribute("message", "账号或密码错误！");
        req.setAttribute("username", username);
        req.getRequestDispatcher("/login.jsp").forward(req, resp);
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
}
